#include "servermonothread.h"

ServerMonothread::ServerMonothread(Service *service, int waitForAnswer)
{
    nextBlockSize = 0;
    this->service = service;
    this->waitForAnswer = waitForAnswer;
}

void ServerMonothread::onReadyRead()
{
    QTcpSocket *tcpSocket = static_cast<QTcpSocket *>(QObject::sender());
    QDataStream in(tcpSocket);

    forever {
        if(nextBlockSize == 0)
        {
            if(tcpSocket->bytesAvailable() < sizeof(quint16))
            {
                return;
            }

            in >> nextBlockSize;
        }

        if(tcpSocket->bytesAvailable() < nextBlockSize)
        {
            return;
        }


        if(waitForAnswer > 0)
        {
            int initialTime = QTime(0, 0, 0).msecsTo(QTime::currentTime());
            int finalTime = initialTime;

            while(finalTime - initialTime < waitForAnswer)
            {
                finalTime = QTime(0, 0, 0).msecsTo(QTime::currentTime());
            }
        }


        QByteArray result = service->execute(in);

        if(!result.isEmpty())
        {
            tcpSocket->write(result);
        }

        nextBlockSize = 0;
        break;
    }
}


void ServerMonothread:: incomingConnection(int handle)
{
    QTcpSocket *client = new QTcpSocket(this);
    connect(client, SIGNAL(readyRead()),this,SLOT(onReadyRead()));
    client->setSocketDescriptor(handle);
}
